//
//  SYDPhotoPickerManager.m
//  PinGJByOwnerSide
//
//  Created by lantaiyuan on 2017/9/6.
//  Copyright © 2017年 lantaiyuan. All rights reserved.
//

#import "SYDPhotoPickerManager.h"
@interface SYDPhotoPickerManager () <UIImagePickerControllerDelegate,
UINavigationControllerDelegate,UIActionSheetDelegate,MShowAllGroupDelegate>

@property (nonatomic, weak)     UIViewController          *fromController;
@property (nonatomic, copy)     HYBPickerCompelitionBlock completion;
@property (nonatomic, copy)     HYBPickerCancelBlock      cancelBlock;
@property (nonatomic, assign)   BOOL      allowEdit;

@end

@implementation SYDPhotoPickerManager

+ (SYDPhotoPickerManager *)shared {
    static SYDPhotoPickerManager *sharedObject = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        if (!sharedObject) {
            sharedObject = [[[self class] alloc] init];
        }
    });
    
    return sharedObject;
}

- (void)showActionSheetInView:(UIView *)inView
               fromController:(UIViewController *)fromController
                    allowEdit:(BOOL)allowEdit
                   completion:(HYBPickerCompelitionBlock)completion
                  cancelBlock:(HYBPickerCancelBlock)cancelBlock {
    self.completion = [completion copy];
    self.cancelBlock = [cancelBlock copy];
    self.fromController = fromController;
    self.allowEdit = allowEdit;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        UIActionSheet *actionSheet = nil;
        if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
            actionSheet  = [[UIActionSheet alloc] initWithTitle:nil
                                                       delegate:(id<UIActionSheetDelegate>)self
                                              cancelButtonTitle:@"取消"
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:@"从相册选择", @"拍照上传", nil ];
        } else {
            actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                      delegate:(id<UIActionSheetDelegate>)self
                                             cancelButtonTitle:@"取消"
                                        destructiveButtonTitle:nil
                                             otherButtonTitles:@"从相册选择", nil ];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [actionSheet showInView:inView];
        });
    });
    
    return;
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if (buttonIndex == 0) {
            //从系统选择图片
            [self loadImgDataAndShowAllGroup];
        } else if (buttonIndex == 1) {// 拍照
            
            if (!imaPic) {
                imaPic = [[UIImagePickerController alloc] init];
            }
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                imaPic.sourceType = UIImagePickerControllerSourceTypeCamera;
                imaPic.delegate = self;
                if (IOS8_OR_LATER) {
                    imaPic.modalPresentationStyle = UIModalPresentationOverCurrentContext;
                }
                WEAKSELF
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.fromController presentViewController:imaPic animated:YES completion:nil];
                });
            }
        }
    });

    return;
}

#pragma mark - UIImagePickerControllerDelegate
// 选择了图片或者拍照了
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    if (IOS8_OR_LATER) {
        picker.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [picker dismissViewControllerAnimated:YES completion:nil];
    });
    
    UIImage *theImage = nil;
    // 判断，图片是否允许修改
    if ([picker allowsEditing]){
        //获取用户编辑之后的图像
        theImage = [info objectForKey:UIImagePickerControllerEditedImage];
    } else {
        // 照片的元数据参数
        theImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
        if (theImage && self.completion) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
        [self.fromController setNeedsStatusBarAppearanceUpdate];
        
        dispatch_async(dispatch_get_main_queue(), ^{
        
            dispatch_async(dispatch_get_main_queue(), ^{
                self.completion(theImage);
            });
        });
    }
    return;
}

// 取消
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)aPicker {
    [aPicker dismissViewControllerAnimated:YES completion:nil];
    
    if (self.cancelBlock) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
        [self.fromController setNeedsStatusBarAppearanceUpdate];  
        
        self.cancelBlock();  
    }  
    return;  
}  

#pragma mark - 加载照片数据
- (void)loadImgDataAndShowAllGroup{
    if (!_arrSelected) {
        self.arrSelected = [NSMutableArray array];
    }
    __block id Obj = _obj;
    [[MImaLibTool shareMImaLibTool] getAllGroupWithArrObj:^(NSArray *arrObj) {
        if (arrObj && arrObj.count > 0) {
            self.arrGroup = arrObj;
            if ( self.arrGroup.count > 0) {
                MShowAllGroup *svc = [[MShowAllGroup alloc] initWithArrGroup:self.arrGroup arrSelected:self.arrSelected];
                svc.delegate = self;
                if ([Obj isKindOfClass:[UINavigationController class]]) {
                    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:svc];
                    if (_arrSelected) {
                        svc.arrSeleted = _arrSelected;
                        svc.mvc.arrSelected = _arrSelected;
                    }
                    svc.maxCout = _maxCount;
                    
                    [self.fromController presentViewController:nav animated:YES completion:nil];
                }
            }
        }
    }];
}
#pragma mark - 完成选择后返回的图片Array(ALAsset*)
- (void)finishSelectImg{
    //正方形缩略图
    NSMutableArray *thumbnailImgArr = [NSMutableArray array];
    
    for (ALAsset *set in _arrSelected) {
        CGImageRef cgImg = [set thumbnail];
        UIImage* image = [UIImage imageWithCGImage: cgImg];
        [thumbnailImgArr addObject:image];
    }
    NSLog(@"frame--------%@",thumbnailImgArr[0]);
    self.completion(thumbnailImgArr[0]);
}
@end







